package com.example.javabasic.thread.classone.demo5;

import java.util.stream.Stream;

import static java.lang.System.*;

/**
 * 生产者消费者模型
 */
public class ProduceConsumer {
    private static final Object L = new Object();
    //用来标记是否已经生产新内容
    private Boolean bool = true;
    private static volatile int i = 1;

    //生产者
    public void produce() {
        synchronized (L) {
            while (bool) {
                try {
                    L.wait();// wait 会释放锁
                } catch (InterruptedException e) {
                    out.println("生产等待异常");
                }
            }
            out.println("生产->" + ++i);
            L.notifyAll();
            bool = true;
        }
    }


    //消费者
    public void consumer() {
        synchronized (L) {
            while (!bool) {
                try {
                    L.wait();
                } catch (InterruptedException e) {
                    out.println("消费等待异常");
                }
            }
            out.println("消费->" + i);
            L.notifyAll();
            bool = false;
        }
    }


    public static void main(String[] args) {
        ProduceConsumer ps = new ProduceConsumer();
        Stream.of("p1", "p2", "p3").forEach(
                i -> {
                    new Thread(() -> {
                        while (true) {
                            ps.produce();
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                            }
                        }
                    }, i).start();
                }
        );
        Stream.of("c1", "c2", "c3").forEach(
                i -> {
                    new Thread(() -> {
                        while (true) {
                            ps.consumer();
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                            }
                        }
                    }, i).start();
                }
        );


    }
}
